//
// Created by 33145 on 2023/6/2.
//

#include "fdevent_group.h"
#include "../common/rocket.h"

namespace rocket {

  static FdEventGroup::ptr g_fd_event_group = nullptr;

  FdEventGroup::FdEventGroup(int size) : _size(size) {
    _fd_group.resize(size);
    for (int i = 0; i < size; i++) {
      _fd_group[i] = std::make_shared<FdEvent>(i);
    }
  }

  FdEvent::ptr FdEventGroup::getFdEvent(int fd) {
    ScopeMutex<Mutex> lock(_mutex);
    if ((size_t) fd < _fd_group.size()) {
      return _fd_group[fd];
    }
    int new_size = int(fd * 1.5);
    for (int i = (int)_fd_group.size(); i < new_size; ++i) {
      _fd_group.push_back(std::make_shared<FdEvent>(i));
    }
    return _fd_group[fd];
  }

  FdEventGroup::ptr FdEventGroup::GetFdEventGroup() {
    if (g_fd_event_group != nullptr) {
      return g_fd_event_group;
    }
    g_fd_event_group = std::make_shared<FdEventGroup>(128);
    return g_fd_event_group;
  }
}
